<template>
<div>
	<div class="bigtitle">
		<div class="bigtitle-title">我的购物车</div>
		<router-link :to="{name:'mall'}" right>继续逛逛 ></router-link>
	</div>
	<div v-if="!isPhone">
		<table border="0" cellspacing="0" cellpadding="0" long text-left mgt3>
			<tr bg-gray4 sz1>
				<td pdx1 pdy3>
					<Checkbox v-model="isSelectAll" @on-change="handleSelectAll">
						<span v-if="!isPhone">全选</span>
					</Checkbox>
				</td>
				<td pdx1 pdy3>商品信息</td>
				<td v-if="!isPhone" pdx1 pdy3>单价</td>
				<td pdx1 pdy3>数量</td>
				<td v-if="!isPhone" pdx1 pdy3>小计</td>
				<td pdx1 pdy3>操作</td>
			</tr>
			<tr v-for="(item, index) in items" :key="index" bdb-gray3>
				<td pdx1 pdy3 bdb-gray4><Checkbox v-model="item.selected" @on-change="handleSelectItem"/></td>
				<td pdx1 pdy3 bdb-gray4>
					<order-detail-profile :detail="item"></order-detail-profile>
				</td>
				<td v-if="!isPhone" pdx1 pdy3 bdb-gray4>
					<p>￥{{formatPrice(item.price)}}</p>
				</td>
				<td pdx1 pdy3 bdb-gray4>
					<div v-if="isPhone">
						<p>单价：￥{{formatPrice(item.price)}}</p>
						<p blue>小计：￥{{formatPrice(item.price * item.count)}}</p>
					</div>
					<p><count v-model="item.count" :min="item.minLimitCount" :max="item.maxLimitCount" :step="1" :disabled="item.inventory==0"/></p>
					<p>
						<span v-if="item.count <= item.minLimitCount" red mgr1>起购量为{{item.minLimitCount}}</span>
						<span v-if="item.count >= item.maxLimitCount" red>限购量为{{item.maxLimitCount}}</span>
					</p>
					<p gray3>{{item.inventory>0?'有货':'无货'}}</p>
				</td>
				<td v-if="!isPhone" pdx1 pdy3 bdb-gray4>
					<p blue>￥{{formatPrice(item.price * item.count)}}</p>
				</td>
				<td pdx1 pdy3 bdb-gray4>
					<p>
						<span v-if="item.isCollected" gray3>已收藏</span>
						<span v-else linkable @click="handleAddCollection(index)">收藏</span>
					</p>
					<p @click='RemoveCommodityFromShoppingCart(index)' red linkable>删除</p>
				</td>
			</tr>
		</table>
		<Row type="flex" justify="start" align="middle" mgt3 pdx1 pdy3 bd-gray4>
			<Col :xs="{ span: 24, offset: 0 }" :sm="{ span: 12, offset: 0 }" sz1 pdx2>
				<Checkbox v-model="isSelectAll" @on-change="handleSelectAll">全选</Checkbox>
				<Button :disabled="selectedCommodityCount<=0" mgr1 @click="handleDeleteSelected">删除选中的商品</Button>
				<Button :disabled="selectedCommodityCount<=0" @click="handleCollecteSelected">移入收藏夹</Button>
			</Col>
			<Col :xs="{ span: 24, offset: 0 }" :sm="{ span: 9, offset: 0 }" text-right>
				<p sz1>已选商品 <span blue>{{selectedCommodityCount}}</span> 件，合计（不含运费）：<span blue sz2>￥{{formatPrice(totalAmount)}}</span></p>
				<p gray3>（商品总价：￥{{formatPrice(totalAmount)}}）</p>
			</Col>
			<Col :xs="{ span: 24, offset: 0 }" :sm="{ span: 3, offset: 0 }" text-center>
				<Button size="large" type="primary" @click="handleSettlement" :disabled="selectedCommodityCount==0" right>去结算</Button>
			</Col>
		</Row>
	</div>
	<div v-else class="full-background" style="height:100vh;margin-bottom:-80px;" bg-gray5>
		<Row>
			<Col v-for="(item, index) in items" :key="index" span="24" bdb-gray4 pdy2 bg-white class="full-background">
				<order-detail-profile :detail="item">
					<div slot="left" w2 h5>
						<Checkbox v-model="item.selected" @on-change="handleSelectItem"/>
					</div>
					<div slot="detail">
						<p>
							<span blue mgr2>￥{{item.price}}</span>
							<span gray3>{{item.inventory>0?'':'库存不足'}}</span>
						</p>
						<count v-model="item.count" size="small"
							:min="item.minLimitCount" :max="item.maxLimitCount" :step="1" :disabled="item.inventory==0" />
					</div>
					<div slot="right" gray3>
						<Button icon="ios-trash-outline" size="small" type="text" linkable sz2 @click='RemoveCommodityFromShoppingCart(index)'></Button>
					</div>
				</order-detail-profile>
			</Col>
		</Row>

		<div style="position:fixed;bottom:0;left:0;" lh4 long pdx2 bg-white bdt-gray4>
			<Checkbox v-model="isSelectAll" @on-change="handleSelectAll" left sz1>全选</Checkbox>
			<div right>
				<span mgr2 sz1>合计：<span blue>￥{{formatPrice(totalAmount)}}</span></span>
				<Button size="large" type="primary" @click="handleSettlement" :disabled="selectedCommodityCount==0">去结算</Button>
			</div>
		</div>
	</div>
</div>
</template>

<script lang="ts">
import { Component, Vue,Inject, Prop,Watch } from 'vue-property-decorator';
import AbpBase from '../../lib/abpbase'
import OrderDetailProfile from '../../components/common/order-detail-profile.vue'
import count from '../../components/common/count.vue'

@Component({
	components: { OrderDetailProfile, count }
})
export default class Shopping extends AbpBase{
	isSelectAll:Boolean = false;
	items:Array<any> = [];
	get selectedCommodityCount() {
		return this.items.reduce((total, elem) => {
			if(elem.inventory > 0 && elem.selected) {
				return total + elem.count;
			}else {
				return total;
			}
		}, 0);
	}
	get totalAmount() {
		return this.items.reduce((total, elem) => {
			if(elem.inventory > 0 && elem.selected) {
				return total + elem.price * elem.count;
			}else {
				return total;
			}
		}, 0);
	}
	async getShoppingCartCommodities() {
		await this.$store.dispatch('shoppingcart/getAll');
		this.items = this.$store.state.shoppingcart.items.map(elem => {
			elem.maxLimitCount = Math.min(elem.maxLimitCount, elem.inventory);
			elem.minLimitCount = Math.min(elem.minLimitCount, elem.maxLimitCount);
			return Object.assign({ selected: false }, elem);
		});
	}
	RemoveCommodityFromShoppingCart(index){
		this.confirm(`确认从购物车移除选中的商品吗？`, async() => {
			var id = this.items[index].id;
			var response = await this.post('ShoppingCart/RemoveCommodityFromShoppingCart', { id: id });
			if(response.success) {
				this.items.splice(index, 1);
			}
		});
	}
	handleDeleteSelected() {
		this.confirm(`确认从购物车批量移除选中的商品吗？`, async() => {
			var ids = [];
			this.items.forEach(elem => {
				if(elem.selected) {
					ids.push(elem.id);
				}
			});
			var response = await this.post('ShoppingCart/RemoveCommodityFromShoppingCart', { ids: ids });
			if(response.success) {
				this.items = this.items.reduce((result, elem) => {
					if(!elem.selected) {
						result.push(elem);
					}
					return result;
				}, []);
			}
		});
	}
	async handleCollecteSelected() {
		var items = this.items.reduce((result, elem) => {
			if(elem.selected && !elem.isCollected) {
				result.push({
					commodityId: elem.commodityId,
					shoppingOptionId: elem.shoppingOptionId
				});
			}
			return result;
		}, []);
		var response = await this.post('Collection/Adds', { items: items });
		if(response.success) {
			this.items.forEach(elem => {
				if(elem.selected) {
					elem.isCollected = true;
				}
			});
		}
	}
	handleSelectAll(value) {
		this.items.forEach(elem => {
			elem.selected = value;
		});
	}
	handleSelectItem(value) {
		for(var i = 0; i < this.items.length; i++) {
			var elem = this.items[i];
			if(elem.selected == false){
				this.isSelectAll = false;
				return;
			}
		}
		this.isSelectAll = true;
	}
	async handleAddCollection(index) {
		var item = this.items[index];
		var response = await this.post('Collection/Add', { commodityId: item.commodityId, shoppingOption: item.shoppingOption });
		if(response.success) {
			item.isCollected = true;
		}
	}
	handleSettlement() {
		var items = this.items.reduce((result, elem) => {
			if(elem.selected) {
				result.push({
					commodityId: elem.commodityId,
					shoppingOptionId: elem.shoppingOptionId,
					count: elem.count
				});
			}
			return result;
		}, []);
		this.$router.push({
			name: 'submit-order',
			query: {
				model: JSON.stringify({
					items: items,
					isFromShoppingCart: true
				})
			}
		});
	}
	created() {
		if(!this.isLogined) {
			this.$router.push({
				name: 'login'
			});
			return;
		}
		this.getShoppingCartCommodities();
	}
}
</script>
